package com.example.myjavafx.controller;

import com.google.gson.JsonObject;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ProductsController {
    @FXML
    public TextArea responseTextArea;

    @FXML
    public void productBtn(ActionEvent actionEvent) {
        System.out.println("产品按钮被点击");
        JsonObject requestBody = new JsonObject();
        // 参数有model, class_name, function_name
        requestBody.addProperty("mode", "initialize");
        requestBody.addProperty("class_name", "KemaiLightController");
        requestBody.addProperty("function_name", "");

        sendPostRequest("/light/init", requestBody);
       // sendPostRequest("/light/init", requestBody);
    }
    private void sendPostRequest(String urlPath, JsonObject requestBody) {
        try {
            URL url = new URL("http://localhost:8080/api/userList"); // 替换为你的服务器地址
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // 发送JSON请求体
            String jsonInputString = requestBody.toString();
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();

                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                // 显示响应在TextArea中
                System.out.println("Response: " + response);
                updateTextArea(response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateTextArea("请求失败: " + e.getMessage());
        }
    }

    private void updateTextArea(String text) {
        responseTextArea.setText(text);
    }
}